package com.zhentao.studyim.netty;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.*;
import lombok.extern.slf4j.Slf4j;

/**
 * CORS跨域处理器
 * 处理WebSocket连接的跨域问题
 */
@Slf4j
public class CorsHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        log.debug("CorsHandler收到消息: {}", msg.getClass().getSimpleName());

        if (msg instanceof FullHttpRequest) {
            FullHttpRequest request = (FullHttpRequest) msg;
            log.debug("HTTP请求: {} {}", request.method(), request.uri());

            // 处理OPTIONS预检请求
            if (HttpMethod.OPTIONS.equals(request.method())) {
                log.debug("处理OPTIONS预检请求");

                FullHttpResponse response = new DefaultFullHttpResponse(
                    request.protocolVersion(),
                    HttpResponseStatus.OK
                );

                response.headers().set("Access-Control-Allow-Origin", "*");
                response.headers().set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
                response.headers().set("Access-Control-Allow-Headers", "*");
                response.headers().set("Access-Control-Max-Age", "3600");
                response.headers().set("Content-Length", "0");

                ctx.writeAndFlush(response);
                return;
            }
        }

        // 继续传递给下一个处理器
        super.channelRead(ctx, msg);
    }
}


